package com.itcast.stargraph.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.stargraph.dto.request.UserLoginReqDTO;
import com.itcast.stargraph.dto.respone.UserLoginResDTO;
import com.itcast.stargraph.mapper.UserMapper;
import com.itcast.stargraph.pojo.User;
import com.itcast.stargraph.service.UserService;
import com.itcast.stargraph.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * TODO
 *
 * @Author katana
 * @Date 2025/6/9 11:22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    
    /**
     * 登录
     *
     * @param loginDTO
     * @return
     */
    @Override
    public UserLoginResDTO login(UserLoginReqDTO loginDTO) {
        //1 根据username或者mobile从用户表中查询到用户信息
        User user = this.lambdaQuery().eq(User::getUsername, loginDTO.getUsername())
                .or().eq(User::getMobile, loginDTO.getUsername())
                .one();
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        //2 验证密码
        boolean result = BCrypt.checkpw(loginDTO.getPassword(), user.getPassword());
        if (!result) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        //3 判断用户状态是否正常
        if (!(user.getStatus() == 0)) {
            throw new RuntimeException("用户状态异常");
        }
        
        //4 生成登录用户令牌
        String token = JWTUtils.createJWT(user.getId(),  user.getUsername());
        
        //5 封装返回结果
        UserLoginResDTO resDTO = new UserLoginResDTO();
        resDTO.setId(user.getId());
        resDTO.setToken(token);
        resDTO.setName(user.getUsername());
        resDTO.setAvatar(user.getAvatar());
        
        return resDTO;
        
    }
}
